class Solution
{
public:
    int findDuplicate(vector<int>& nums)
    {
        int slow = 0, fast = 0;
        while (true)
        {
            slow = nums[slow];
            fast = nums[nums[fast]];
            if (slow == fast)
            {
                break;
            }
        }

        int head = 0;
        while (slow != head)
        {
            slow = nums[slow];
            head = nums[head];
        }
        return slow;
    }
};